/* eslint-disable no-tabs */
/* eslint-disable quotes */
import { insertMoment, nextTick } from '../../lib/utils.js';
import { openFakeWin } from "./tool.js";
import { asyncSetInterval } from '../../lib/zeroReportUtils.js';
let currentZeroInfo;
let cssStyle = `
    .table-box table {
        border-collapse: collapse;
        width: 100%;
        font-size: 14px;
        color: #333;
    }
    .table-box table input {
        background: #fff;
        text-align: right;
        width: 100%;
        border: none;
    }
    .table-box td {
        border: 1px solid #ddd;
    }
    .table-box .hidden {
        display: none;
    }
    .table-box table .txt-indent-2 {
        text-indent: 2em;
    }

    .table-box table .txt-indent-4 {
        text-indent: 4em;
    }
    .table-box table .txt-indent-6 {
        text-indent: 6em;
    }
    .table-box table thead td {
        border: none;
    }
    .table-box .table-title {
        text-align: center;
    }
    .table-box .mini-checkboxlist-item {
        display: inline-block;
    }
    .table-box .mini-checkboxlist-item input {
        width: auto;
    }
    .table-box .mini-checkboxlist-item label {
        display: inline-block;
    }
`;

const getQysdsLi = () => {
  let tds = $('#wddb tr');
  let qysdsIsReport = window.sessionStorage.getItem('qysdsIsReport');
  if (parseInt(qysdsIsReport) === 1) return false;
  return Array.from(tds).find(item => $(item).find('td:eq(0)').text() === '企业所得税申报');
};

const qysdsReprotQ = () => {
  nextTick(() => {
    let lis = $('#secondMenu li a');
    if (lis.length) {
      let qysdsCzzs = Array.from(lis).find(item => $(item).text() === '居民企业（查账征收）企业所得税月（季）度申报');
      // if (qysdsCzzs) qysdsCzzs.click();
      openFakeWin('null', 'F251000200000220', '居民企业（查账征收）企业所得税月（季）度申报', '102261');
      setTimeout(() => {
        window.close();
      }, 2000);
      return true;
    }
  });
};

const qysdsReprot = (data) => {
  currentZeroInfo = data;
  nextTick(() => {
    let info = document.querySelector('#sbzlmc').innerText;
    if (info === '居民企业（查账征收）企业所得税月（季）度申报') {
      document.querySelector('#btnBzb').click();
      return true;
    }
  });
};

const miniMessagebox = async () => {
  return new Promise((reslove, reject) => {
    let timer = setInterval(() => {
      let messagebox = $('.mini-messagebox');
      if (messagebox.length) {
        let btns = $('.mini-messagebox .mini-panel-footer .mini-messagebox-buttons .mini-button');
        let sureBtn = Array.from(btns).find(item => $(item).text() === '确定');
        if (sureBtn && $(sureBtn).text() === '确定') {
          clearInterval(timer);
          timer = null;
          $(sureBtn).click();
          reslove();
        }
      }
    }, 200);
  });
};

const qysdsReprotTable = async ({ endPeriod, quarterSum, endSum }) => {
  await closeBtn(2000);
  let tabs = '';
  return asyncSetInterval(() => {
    tabs = $('#tabs table.mini-tabs-header  tr>td.mini-tab');
    if (tabs.length) {
      tabs = Array.from(tabs);
      return true;
    }
  }, 1000).then(() => {
    let A20000 = tabs.find(item => $(item).text().includes('A200000中华人民共和国企业所得税月'));
    A20000.click();
    let table = $('#table_001');
    return asyncSetInterval(async() => {
      let idNess = '#001_9_';
      let idNess1 = '#001_10_';
      let n = 1;
      if (endPeriod === 6) n = 3;
      if (endPeriod === 9) n = 5;
      if (endPeriod === 12) n = 7;
      $(idNess + n).val(1);
      $(idNess + (n + 1)).val(1);
      if (parseFloat(quarterSum)) $(idNess1 + n).val(parseFloat(quarterSum));
      else if (!parseFloat($(idNess1 + n).val())) $(idNess1 + n).val(parseFloat(0.01));
      if (parseFloat(endSum)) $(idNess1 + (n + 1)).val(parseFloat(endSum));
      else if (!parseFloat($(idNess1 + (n + 1)).val())) $(idNess1 + (n + 1)).val(parseFloat(0.01));
      ['国家限制或禁止行业', '高新技术企业', '技术入股递延纳税事项'].forEach(i => {
        let gjxzhzzhy = Array.from($(table).find("tbody > tr")).find((item) =>
          $(item).find("td:nth-child(1)").text().includes(i));
        let input = $(gjxzhzzhy).find(
          ".enable.txt-l .mini-list-inner > div:nth-child(2) > input"
        );
        Array.from(input).forEach((item) => item.click());
      });
      $('#sb_tempSaveCheck').click();
      await closeBtn();
      return true;
    }, 1000).then(() => {
      let A201010 = tabs.find(item => $(item).text().includes('A201010免税收入、减计收入、所得减免等优惠明细表（附表一）'));
      A201010.click();
      return asyncSetInterval(async () => {
        $('#sb_tempSaveCheck').click();
        await closeBtn();
        return true;
      }, 1000);
    }).then(() => {
      let A201020 = tabs.find(item => $(item).text().includes('A201020 资产加速折旧、摊销(扣除)优惠明细表（附表二）'));
      A201020.click();
      return asyncSetInterval(async () => {
        $('#sb_tempSaveCheck').click();
        await closeBtn();
        return true;
      }, 1000);
    }).then(() => {
      let A201030 = tabs.find(item => $(item).text().includes('A201030减免所得税优惠明细表（附表三）'));
      A201030.click();
      return asyncSetInterval(async () => {
        $('#sb_tempSaveCheck').click();
        await closeBtn();
        return true;
      }, 1000);
    })
      .then(() => {
        let A201030 = tabs.find(item => $(item).text().includes('居民企业参股外国企业信息报告表'));
        A201030.click();
        return asyncSetInterval(async () => {
          $('#sb_tempSaveCheck').click();
          await closeBtn();
          return true;
        }, 1000);
      })
      .then(() => {
        let A201030 = tabs.find(item => $(item).text().includes('技术成果投资入股企业所得税递延纳税备案表'));
        A201030.click();
        return asyncSetInterval(async () => {
          $('#sb_tempSaveCheck').click();
          await closeBtn();
          return true;
        }, 1000);
      })
      .then(() => {
        return asyncSetInterval(async () => {
          $('#sb_save').click();
          await closeBtn(2000);
          await closeBtn(2000);
        }, 1000);
      });
  });
};

async function closeBtn(time = 1000) {
  return asyncSetInterval(() => {
    let btns = $('.mini-messagebox .mini-button');
    let surebtn = Array.from(btns).find(item => $(item).text().includes('确定'));
    if (surebtn) {
      surebtn.click();
      return true;
    }
  }, time);
}

const qysdsReprotQuery = (data) => {
  nextTick(() => {
    if (document.querySelector("#search-btn")) {
      document.querySelector("#search-btn").click();
      nextTick(() => {
        let trs = document.querySelectorAll("#mini-grid-table-bodysbjgcx_grid > tbody > tr");
        if (trs.length) {
          let qysds = Array.from(trs).find(item => item.querySelector('td:nth-child(2)').innerText === '企业所得税A类季报');
          if (qysds) {
            let scanBtn = qysds.querySelector('td:nth-child(9) > span:nth-child(2) > a');
            scanBtn.click();
            // 同步申报表
            asyncTableList();
          }
          return true;
        }
      });

      // 同步申报表

      return true;
    }
  });
};

const asyncTableList = () => {
  nextTick(() => {
    let iframe = document.querySelector("body > div.fixedWindowTop0 > div > div.mini-panel-viewport > div.mini-panel-body > iframe");
    if (iframe) {
      iframe.onload = () => {
        window.__iframe_onload1();
        nextTick(() => {
          let contents = iframe.contentDocument.querySelectorAll("#tabs > table > tbody > tr > td:nth-child(2) > div.mini-tabs-bodys > div");
          if (contents.length) {
            let tables = Array.from(contents);
            asyncTable(tables);
            return true;
          }
        });
      };
      return true;
    }
  });
};
const asyncTable = async (tables) => {
//   let table1 = tables[0];
  for (let i = 0; i < tables.length; i++) {
    let table = tables[i];
    let tableContent = {
      declareType: '企业所得税',
      title: table.querySelector('table').getAttribute('sb_title'),
      html: table.innerHTML,
      css: cssStyle
    };
    saveTableDetail(tableContent, i);
  }
  setTimeout(() => {
    window.postMessage(
      {
        event: "baoBiaoDetailBack",
        data: {
          type: 'qysds',
          isclose: true,
          lastTime: 200
        }
      },
      "*"
    );
  }, 1000);
};

// 保存明细表
const saveTableDetail = (tableContent) => {
  window.postMessage(
    {
      event: 'asyncTableDetail',
      data: tableContent
    },
    '*'
  );
};


export {
  getQysdsLi, qysdsReprot, qysdsReprotTable, qysdsReprotQuery, qysdsReprotQ
};
